from fastapi import APIRouter
from openai.types.shared import metadata
from APP.config.log_conf import log
from APP.common.respones.response_schema import response_base
from APP.app.userprofile.services.emp_cap_service import EmpCapService
from agno.agent import Agent,RunResponse
from agno.models.openai.like import OpenAILike
from agno.tools.reasoning import ReasoningTools
from agno.tools.thinking import ThinkingTools
from APP.app.userprofile.schemas.agent_schema import EmpCompetencyModel
from APP.utils.agent import get_embedder
from agno.vectordb.chroma import ChromaDb
from agno.knowledge.pdf import PDFKnowledgeBase,PDFReader
from APP.utils.timezone import timezone

emp_competency_router = APIRouter()

@emp_competency_router.post('/empcap', summary='生成员工胜任力评估模型结果', description='根据员工标签生成员工与岗位胜任力评估模型结果')
async def generate_emp_competency():


    emp_cap_dict =await EmpCapService.get_comp_eval(1,2)

    cap_desc = ''
    m_index = 1
    for key, value in emp_cap_dict.items():
        
        name = value['name']
        desc = value['desc']
        result = value['result']
        if result == '优势':
            cap_desc += f"{m_index}.{name}:要求{desc}，员工在此方面能力是{result}，高于岗位标准，主要体现在："
        else:
            cap_desc += f"{m_index}.{name}:要求{desc}，员工在此方面能力是{result}，低于岗位标准，主要体现在："

        detail = value['detail']
        index = 1
        for sub_key, sub_value in detail.items():
            sub_name = sub_value['name']
            sub_desc = sub_value['desc']
            context = sub_value['context'].strip()
            cap_desc += f"({index}).{sub_name}：{sub_desc}，具体经验有{context}"
            index += 1 
        #在for循环结束的时候cap_desc增加换行符
        cap_desc += '\n'
        m_index += 1
    
    # print(cap_desc)
    agent = Agent(
        model=OpenAILike(
            id="deepseek-ai/DeepSeek-R1-0528",
            api_key='d986cabb-c3de-42c8-ba7a-d124ed7dc5cd',
            base_url="https://api-inference.modelscope.cn/v1/",
        ),
        tools=[ThinkingTools(add_instructions=True)],
        description='你是一个人力资源管理大师，根据员工能力指标判断是否胜任岗位',
        instructions=[
            '从人力资源的角度根据岗位的各项指标要求及员工在每个指标内的表现情况，综合评估该员工张三是否胜任此市场开发部经理岗位，'
            '岗位的各项指标要求及员工在每个指标内的表现情况如下：'
            f'{cap_desc}',
            '要求逐项分析岗位指标与员工的匹配度，对优势指标进行重点关注，对劣势指标进行重点分析并提出发展建议，'
            '并根据分析结果综合判断员工是否胜任岗位'
        ],
        use_json_mode=True,
        show_tool_calls=True,
        response_model=EmpCompetencyModel,  
        # markdown=True,
    )
    
    agent.print_response('分析员工张三是否胜任市场开发部经理岗位',stream=True)
    # response:RunResponse = agent.run('分析员工张三是否胜任市场开发部经理岗位')
    # emp_competency:EmpCompetencyModel = response.content
    # print(f'员工张三的胜任力评估模型结果为：{emp_competency.competency}')
    # print(f'员工张三的核心优势评估模型结果为：{emp_competency.core_advantage}')
    # print(f'员工张三的不足建议评估模型结果为：{emp_competency.insufficient_suggestion}')
    # print(f'员工张三的发展路径建议评估模型结果为：{emp_competency.suggestion}')


    return response_base.success()

@emp_competency_router.post('/knowledgebase', summary='企业员工知识库', description='将企业、员工各种文档资料向量化')
async def knowledge_base():
    '''
    员工知识库
    参数：员工id，文档url
    '''

    vector_db = ChromaDb(
        collection='emp_knowledge',
        path='embedding_db',
        embedder=get_embedder(),
        persistent_client=True, #持久化向量客户端
    )

    pdf_knowledge_base = PDFKnowledgeBase(
        vector_db=vector_db,
        # path='files/emp',
        path=[
            {
                'path':'files/emp/zcwj.pdf',
                'metadata':{
                    'source':'files/emp/zcwj.pdf',
                    'title':'关于促进半导体行业高质量发展的若干政策',
                    'author':'张三',
                    'date':timezone.t_str(timezone.now()),
                }
            }
        ],
        reader=PDFReader(chunk=True),
    )
    pdf_knowledge_base.load(recreate=True)

    return response_base.success()

